package com.whut.whw.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * <pre>
 *     author : 杨丽金
 *     time   : 2017/06/09
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public abstract class BaseFragment extends Fragment implements FragmentCallback {
    protected View rootView;
    protected LayoutInflater layoutInflater;
    protected Context context;
    // 封装了一些常见的公用方法，供子类调用，用的时候先get再调用方法getUiDelegate()
    protected UiDelegate uiDelegate;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        // 获取该Fragment的活动（Activity）上下文
        if (context instanceof Activity) {
            this.context = (Activity) context;
        }
    }

    /**
     * 绑定布局，初始化控件
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        layoutInflater = inflater;
        if(rootView ==null){
            rootView = initView(inflater);
            // 初始化数据
            initData(savedInstanceState);
            // 设置监听事件
            setListener();
        }
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(rootView!=null){
            ((ViewGroup)rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    /**
     * Activity和Fragment取消绑定
     */
    @Override
    public void onDetach() {
        super.onDetach();
        context = null;
    }

    /**
     * 获得根布局
     *
     * @return
     */
    public View getRootView() {
        return rootView;
    }

    protected UiDelegate getUiDelegate() {
        if (uiDelegate == null) {
            uiDelegate = UiDelegateBase.create(getContext());
        }
        return uiDelegate;
    }

}
